export const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8081'

interface RequestOptions extends RequestInit {
  params?: Record<string, string | number>
  /**
   * Next.js fetch options for caching/ISR and tagging.
   * Keep as any to avoid importing Next types on the client bundle.
   */
  next?: any
  /**
   * Optional revalidate seconds (shorthand for next: { revalidate })
   */
  revalidate?: number
  /**
   * Optional request timeout in milliseconds
   */
  timeoutMs?: number
}

class ApiClient {
  private baseUrl: string

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl
  }

  private async request<T>(
    endpoint: string,
    options: RequestOptions = {}
  ): Promise<T> {
    const { params, headers, next, revalidate, timeoutMs, ...rest } = options

    let url = `${this.baseUrl}${endpoint}`

    // 添加查询参数
    if (params) {
      const entries = Object.entries(params).filter(([, value]) => value !== undefined && value !== null && String(value) !== "")
      const searchParams = new URLSearchParams(
        entries.map(([key, value]) => [key, String(value)])
      )
      url += `?${searchParams.toString()}`
    }

    const controller = new AbortController()
    const id = timeoutMs ? setTimeout(() => controller.abort(), timeoutMs) : undefined

    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
      // Credentials by default omitted; override per-call if needed
      credentials: rest.credentials ?? 'same-origin',
      signal: controller.signal,
      // Next.js specific options for caching/ISR
      next: revalidate != null ? { revalidate } : next,
      ...rest,
    }).finally(() => {
      if (id) clearTimeout(id)
    })

    if (!response.ok) {
      let errorMessage = `API Error: ${response.status}`
      try {
        const contentType = response.headers.get('content-type') || ''
        if (contentType.includes('application/json')) {
          const data = await response.json()
          if (data?.message) errorMessage = data.message
        } else {
          const text = await response.text()
          if (text) errorMessage = text
        }
      } catch (_) {
        // noop
      }
      throw new Error(errorMessage)
    }

    const contentType = response.headers.get('content-type') || ''
    if (contentType.includes('application/json')) {
      return response.json()
    }
    // @ts-expect-error allow non-json response
    return response.text ? response.text() : (undefined as unknown as T)
  }

  // GET 请求
  async get<T>(endpoint: string, options?: RequestOptions): Promise<T> {
    return this.request<T>(endpoint, { ...options, method: 'GET' })
  }

  // POST 请求
  async post<T>(endpoint: string, data?: unknown, options?: RequestOptions): Promise<T> {
    return this.request<T>(endpoint, {
      ...options,
      method: 'POST',
      body: JSON.stringify(data),
    })
  }

  // PUT 请求
  async put<T>(endpoint: string, data?: unknown, options?: RequestOptions): Promise<T> {
    return this.request<T>(endpoint, {
      ...options,
      method: 'PUT',
      body: JSON.stringify(data),
    })
  }

  // DELETE 请求
  async delete<T>(endpoint: string, options?: RequestOptions): Promise<T> {
    return this.request<T>(endpoint, { ...options, method: 'DELETE' })
  }

  // 文件上传
  async upload<T>(file: File): Promise<T> {
    const formData = new FormData()
    formData.append('file', file)

    const response = await fetch(`${this.baseUrl}/api/upload/file`, {
      method: 'POST',
      body: formData,
    })

    if (!response.ok) {
      throw new Error(`Upload Error: ${response.status}`)
    }

    return response.json()
  }
}

export const apiClient = new ApiClient(API_BASE_URL)

// ==================== 类型定义 ====================

export interface Post {
  id: string
  title: string
  content: string
  author: string
  createdAt: string
  updatedAt: string
}
export interface CarPost extends Post {
  price: number 
  image: string
  description: string
  year?: number
  mileage?: number
  color?: string
}

export interface User {
  id: string
  username: string
  email: string
  role: string
  createdAt?: string
}

export interface UserInfo {
  userId: number
  nickname: string
  username: string
  role: number
  roleName: string
}

export interface LoginResponse {
  code: number
  message: string
  data: UserInfo
}

export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

// ==================== API 服务 ====================

export const postService = {
  // 获取帖子列表
  getAll: () => apiClient.get<Post[]>('/api/posts', { revalidate: 60 }),

  // 获取已发布的帖子列表（支持分页和筛选）
  getAllPublished: (params?: { page?: number; size?: number; keyword?: string; category?: string; }) =>
    apiClient.get<any>('/api/posts/list', { params, revalidate: 120 }),

  // 根据用户 ID 获取帖子列表（支持分页）
  getListById: (userId: string, params?: { page?: number; size?: number }) =>
    apiClient.get<any>(`/api/posts/user/${userId}`, { params }),

  // 获取单个帖子详情
  getById: (postId: string | number) => apiClient.get<any>(`/api/posts/${postId}`),

  // 创建帖子
  create: (data: Partial<Post>) => apiClient.post<Post>('/api/posts/add', data),

  // 更新帖子
  update: (id: string, data: Partial<Post>) => apiClient.put<Post>(`/api/posts/${id}`, data),
    // 删除帖子
  delete: (id: string) => apiClient.delete(`/api/posts/${id}`),
}

export const userService = {
  // 获取用户列表
  getAll: () => apiClient.get<User[]>('/api/users'),
  
  // 获取单个用户
  getById: (id: string) => apiClient.get<User>(`/api/users/${id}`),
  
  // 创建用户
  create: (data: Partial<User>) => apiClient.post<User>('/api/users', data),
  
  // 更新用户
  update: (id: string, data: Partial<User>) => apiClient.put<User>(`/api/users/${id}`, data),
  
  // 删除用户
  delete: (id: string) => apiClient.delete(`/api/users/${id}`),
}

export const authService = {
  // 登录
  login: (username: string, password: string) => 
    apiClient.post<LoginResponse>('/api/auth/login', { username, password }),
  
  // 登出
  logout: () => apiClient.post('/api/auth/logout'),
}
